<template>
    <el-row style="height: 100%;">
        <!-- 笔记本栏 -->
        <el-col :span="4" style="background-color: #545c64;">
            <div style="height: 90%;">
                <!-- 头部 -->
                <el-card shadow="never" style="padding: 0;margin: 0;background-color: #545c64;border: none;">
                    <div class="card-header">
                        <span style="color: white;font-weight: 500;">笔记本</span>
                        <el-icon @click="openAddForm" color="#f7d003" :size="16" style="cursor: pointer;">
                            <plus />
                        </el-icon>
                    </div>
                </el-card>
                <!-- 笔记本列表 -->
                <el-menu active-text-color="#ffd04b" background-color="#545c64" text-color="#fff"
                    :default-active="currentNotebook" @select="notebookSelect">
                    <div style="max-height: calc(100vh - 150px);overflow-y: auto;">
                        <el-menu-item :index="nb" v-for="nb in notebooks">
                            <el-icon>
                                <icon-menu />
                            </el-icon>
                            <span>{{nb}}</span>
                        </el-menu-item>
                    </div>
                </el-menu>
            </div>

            <!-- 底部 -->
            <el-card shadow="never" style="padding: 0;margin: 0;background-color: #545c64;border: none;">
                <div class="card-header" style="justify-content: center;">
                    <el-button type="primary" size="small" round @click="syncToCloud">
                        <el-icon>
                            <upload-filled />
                        </el-icon>
                        同步到云端
                    </el-button>
                    <el-button type="success" size="small" round @click="downToLocal">
                        <el-icon>
                            <download />
                        </el-icon>
                        同步到本地
                    </el-button>
                </div>
            </el-card>
        </el-col>

        <!-- 笔记栏 -->
        <el-col :span="5" style="background-color: #f4f5f6;">
            <el-card shadow="never" style="padding: 0;margin: 0;background-color: #f4f5f6;">
                <div class="card-header">
                    <span style="color: deepskyblue;font-weight: 500;">笔记</span>
                    <div>
                        <el-icon @click="removeNote" color="red" :size="16" style="cursor: pointer;margin-right: 20px;">
                            <minus />
                        </el-icon>
                        <el-icon @click="newNote" color="blue" :size="16" style="cursor: pointer;">
                            <plus />
                        </el-icon>
                    </div>
                </div>
            </el-card>

            <el-menu background-color="#f4f5f6" :default-active="currentNote" @select="noteSelect">
                <div style="max-height: calc(100vh - 65px);overflow-y: auto;">
                    <el-menu-item :index="note" v-for="note in notes">
                        <span>{{note}}</span>
                    </el-menu-item>
                    <!-- <el-menu-item index="Ubuntu美化2">
                        <span>Ubuntu美化2</span>
                    </el-menu-item>
                    <el-menu-item index="Ubuntu美化3">
                        <span>Ubuntu美化3</span>
                    </el-menu-item> -->

                </div>
            </el-menu>
        </el-col>

        <!-- 编辑器 -->
        <el-col :span="15">
            <div v-if="showMdEditor">
                <el-form :inline="true" style="margin: 0;text-align: center;">
                    <el-form-item style="margin: 0;margin-right: 0;margin-bottom: 0;width: 99%;">
                        <el-input v-model="mdTitle" placeholder="文章标题" style="width: 100%;height: 35px;padding: 2px 0;">
                        </el-input>
                    </el-form-item>
                </el-form>
                <v-md-editor v-model="mdText" height="94vh" @save="saveMdText"></v-md-editor>
            </div>
        </el-col>
    </el-row>

    <!-- 弹出表单 -->
    <el-dialog v-model="addFormVisible" title="请输入">
        <el-form>
            <el-form-item label="新笔记本名称:">
                <el-input v-model="newNotebookName" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span>
                <el-button @click="addFormCancel">取消</el-button>
                <el-button type="primary" @click="addFormOk">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts">
    import { defineComponent } from 'vue';
    import { Plus, Minus, Download, UploadFilled } from '@element-plus/icons-vue'
    import { ElMessageBox, ElMessage } from 'element-plus'

    export default defineComponent({
        components: { Plus, Minus, Download, UploadFilled, },
        data() {
            return {
                notebooks: [],  // 笔记本列表数据
                notes: [],  // 笔记列表数据
                currentNotebook: '',    // 当前选中笔记本
                currentNote: '',    // 当前选中笔记
                mdTitle: '',    // 文章/笔记 标题
                mdText: '',    // 文章/笔记 内容
                addFormVisible: false,  // 是否显示添加表单
                newNotebookName: '',    // 新建笔记本名称
                showMdEditor: false,    // 是否显示编辑器
                newNoteMdFileName: '',  // 新建笔记文件名（临时）
                notEditedMdtext: '',    // 未编辑时（原始）的Markdown文本
            };
        },
        mounted() {
            this.getNotebookDateForJG();
        },
        methods: {
            // 从坚果云获取笔记本数据
            getNotebookDateForJG() {
                window.go.main.App.GetJGTestDir().then((res) => {
                    // console.log(res);
                    if (res && res.code == 200) {
                        this.notebooks = res.data;
                    } else {
                        ElMessage.error('获取云端数据失败：' + res.msg);
                    }
                });
            },

            // 笔记本被选中
            notebookSelect(key, keyPath) {
                var oldSelectNotebook = this.currentNotebook;
                console.log("选中key：" + key);
                // console.log(keyPath);
                if (this.mdText && key != oldSelectNotebook && this.mdText != this.notEditedMdtext) {  // 编辑器有文本
                    ElMessageBox.confirm(
                        '编辑器文本未保存，是否丢弃？',
                        '警告',
                        {
                            confirmButtonText: '丢弃',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }
                    ).then(() => {
                        ElMessage({
                            type: 'info',
                            message: '已丢弃',
                        });
                        this.mdText = '';
                        this.showMdEditor = false;
                        this.currentNote = '';
                    }).catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '操作取消',
                        });
                        this.currentNotebook = oldSelectNotebook;
                        return;
                    });
                }
                this.currentNotebook = key;

                // 调用go方法获取笔记本下的全部笔记
                window.go.main.App.GetJGTestDirFile(this.currentNotebook).then((res) => {
                    // console.log(res);
                    if (res && res.code == 200) {
                        var data = res.data;
                        this.notes = data.map(n => n.replace('.md', ''));
                    } else {
                        ElMessage.error('获取数据失败：' + res.msg);
                    }
                });
            },
            // 笔记被选中
            noteSelect(key, keyPath) {
                console.log("选中key：" + key);
                // console.log(keyPath);
                // key = key.replace('.md', '');
                this.currentNote = key;

                window.go.main.App.ReadNoteFile(this.currentNotebook, this.currentNote).then((res) => {
                    // console.log(res);
                    if (res && res.code == 200) {
                        var data = res.data;
                        this.mdText = data;
                        this.notEditedMdtext = data;    // 原始笔记内容
                        this.mdTitle = this.currentNote;
                        this.showMdEditor = true;
                    } else {
                        ElMessage.error('读取失败：' + res.msg);
                    }
                });

            },
            // 打开弹出表单
            openAddForm() {
                this.newNotebookName = '';
                this.addFormVisible = true;
            },
            // 弹出表单取消
            addFormCancel() {
                this.addFormVisible = false;
                this.newNotebookName = '';
            },
            // 弹出表单确认,创建笔记本
            addFormOk() {
                // 创建笔记本
                var bookName = this.newNotebookName.trim();
                window.go.main.App.CreateNotebook(bookName).then((res) => {
                    // console.log(res);
                    if (res && res.code == 200) {
                        ElMessage.success('笔记本创建成功');
                        this.notebooks.push(bookName);
                        this.currentNotebook = bookName;
                        this.newNotebookName = '';
                        this.addFormVisible = false;
                    } else {
                        ElMessage.error('笔记本创建失败：' + res.msg);
                    }
                });
            },
            // 新建笔记
            newNote() {
                // console.log('newNote...');
                if (this.currentNotebook) {
                    window.go.main.App.CreateNoteFile(this.currentNotebook).then((res) => {
                        // console.log(res);
                        if (res && res.code == 200) {
                            var fileName = res.data;
                            ElMessage.success('笔记创建成功：' + fileName);
                            this.newNoteMdFileName = fileName;
                            this.notes.push(fileName);
                            this.currentNote = fileName;
                            // console.log('currentNote==', this.currentNote);
                        } else {
                            ElMessage.error('笔记创建失败：' + res.msg);
                        }
                    });
                }
            },
            // 保存文章/笔记
            saveMdText(MdText, html) {
                // console.log(MdText);
                // console.log(html);
                if (!this.mdTitle) {    //没有标题
                    return;
                }
                if (this.currentNotebook && this.currentNote) { // 不为空
                    // 调用go方法保存笔记
                    window.go.main.App.SaveNote(this.currentNotebook, this.newNoteMdFileName, this.mdTitle, MdText).then((res) => {
                        if (res && res.code == 200) {
                            ElMessage.success("笔记保存成功");

                            // 重新获取笔记列表
                            window.go.main.App.GetJGTestDirFile(this.currentNotebook).then((res) => {
                                if (res && res.code == 200) {
                                    var data = res.data;
                                    this.notes = data.map(n => n.replace('.md', ''));
                                } else {
                                    ElMessage.error('获取笔记列表失败：' + res.msg);
                                }
                            });
                        } else {
                            ElMessage.error('笔记保存失败：' + res.msg);
                        }
                    });
                } else {  // 存在为空情况
                    ElMessage.error('');
                }
            },
            // 删除笔记
            removeNote() {
                console.log('删除笔记');
                if (this.currentNotebook == '' || this.currentNote == '') {
                    ElMessage({
                        message: '请选择笔记',
                        type: 'warning',
                    });
                    return;
                }
                ElMessageBox.confirm(
                    `确认删除 ${this.currentNotebook} / ${this.currentNote} 笔记吗？`,
                    '警告',
                    {
                        confirmButtonText: '删除',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                ).then(() => {
                    // 点击了确定，开始删除
                    window.go.main.App.RemoveNote(this.currentNotebook, this.currentNote).then((res) => {
                        if (res && res.code == 200) {
                            ElMessage({
                                type: 'success',
                                message: '删除成功',
                            });
                            // 调用go方法重新获取笔记本下的全部笔记
                            window.go.main.App.GetJGTestDirFile(this.currentNotebook).then((res) => {
                                if (res && res.code == 200) {
                                    var data = res.data;
                                    this.notes = data.map(n => n.replace('.md', ''));
                                } else {
                                    ElMessage.error('获取数据失败：' + res.msg);
                                }
                            });
                        } else {
                            ElMessage.error('删除失败：' + res.msg);
                        }
                    });
                }).catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消操作',
                    });
                });
            },
            // 同步到云端
            syncToCloud() {
                window.go.main.App.SyncToCloud().then((res) => {
                    if (res && res.code == 200) {
                        ElMessage({
                            type: 'success',
                            message: '同步成功',
                        });
                    } else {
                        ElMessage.error('同步失败：' + res.msg);
                    }
                });
            },
            // 同步到本地
            downToLocal() {
                window.go.main.App.DownToLocal().then((res) => {
                    if (res && res.code == 200) {
                        ElMessage({
                            type: 'success',
                            message: '同步成功',
                        });
                    } else {
                        ElMessage.error('同步失败：' + res.msg);
                    }
                });
            },

        },
    });

</script>

<style>
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
</style>